import Qs from 'qs'
import cacheAdapter from './axios-cache-adapter'
import LRUCache from 'lru-cache'

const cacheCfg = new LRUCache({
  maxAge: process.env.cacheTime,
  max: process.env.cacheMax
})

export default function ({ $axios }, inject) {
  // Create a custom axios instance
  const api = $axios.create({
    headers: {
      // common: { Accept: 'text/plain, */*' },
      'Cache-Control': 'no-cache'
    },
    adapter: cacheAdapter($axios.defaults.adapter, {
      enabledByDefault: process.env.cache || false,
      defaultCache: cacheCfg,
      cacheFlag: 'cache'
    })
  })

  api.onRequest(config => {
    if (config.method === 'post') {
      api.defaults.transformRequest = [function (data) {
        data = Qs.stringify(data)
        return data
      }]
    }
    const _params = config.params || config.data
    if (process.env.debug) {
      console.log('Making request to %s, the params is %s.', config.baseURL + config.url, JSON.stringify(_params))
    }
  })

  api.onResponse(response => {
    const { status, statusText, data } = response
    if (process.env.debug) {
      console.log('Response is done. the code is %s, the message is %s.', status, statusText)
      console.log('The response data is: %s. ', JSON.stringify(data))
    }
    return data
  })
  // Inject to context as $api
  inject('api', api)
}